var googleMap, barMarkers = [], jsonListBars, currentInfowindow;

function displayMap() {
   
  var myOptions = {
      center: new google.maps.LatLng(48.856869,2.346641),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    switchBarsView('map');
    if (document.getElementById("maps_canvas")) {
      return;
    }
    $('#home-bars-mapview').html('<div id="maps_canvas" class="maps_canvas"></div>');
    
    
    $('#maps_canvas').width($('#slider').width() + 'px');
    $('#maps_canvas').height(Math.round(($(window).height()) * 3 / 4) + 'px');
    googleMap = new google.maps.Map(document.getElementById("maps_canvas"),
        myOptions);
    
    $.getJSON('/writeBarsJson', handlerJsonListBar);
   
    
  
}

function handlerJsonListBar(data) {
  jsonListBars = data;
  var image = new google.maps.MarkerImage('media/images/beer-icon.png',
      new google.maps.Size(40, 45));
  for (var i = 0; i < data.length; i++) {
    var myLatlng = new google.maps.LatLng(jsonListBars[i]['fields']['latitude'],
        jsonListBars[i]['fields']['longitude']);

    barMarkers[i] = new google.maps.Marker({
      position: myLatlng,
      icon: image,
      title: jsonListBars[i]['fields']['name']
    });
    barMarkers[i].setMap(googleMap);
    var handlerMarkerClick = (function (i) {
        return function() {
          openInfoWindows(i);
        }
      }) (i);
      google.maps.event.addListener(barMarkers[i], 'click',
          handlerMarkerClick);
  }
  
}

function openInfoWindows(i) {
  if (currentInfowindow) currentInfowindow.close();
  var contentString = '<a href="bar/' + jsonListBars[i]['fields']['name'] + '">'
	    + '<div class="bubbleContent"><span class="bubbleTitle">' + jsonListBars[i]['fields']['name'] + '</span><br/>'
	    + '<span class="bubbleAddress">' + jsonListBars[i]['fields']['address']
        + ' > </span></div></a>';

  currentInfowindow = new google.maps.InfoWindow({
    content: contentString
  });
  currentInfowindow.open(googleMap, barMarkers[i]);
}

function switchBarsView(view) {
  if (view == 'list') {
    $('#home-bars-mapview').hide();
    $('#home-bars-listview').show();    
  } else {
    $('#home-bars-mapview').show();
    $('#home-bars-listview').hide();
  }
}

function saveCoordinate(latitude, longitude) {
  $.ajax({
    type: 'POST',
    url: '/saveCoordinate',
    data: {'latitude' : latitude, 'longitude' : longitude},
    success: function(data) {
      var jsonObj = $.parseJSON(data);
      $('#home-wrapper').html(jsonObj['page'])
      $('#home-wrapper').trigger('create');
    },
  });
}

